﻿Imports System.Linq.Expressions
Imports System.Reflection
Imports System.Runtime.CompilerServices

Public Module Extensions
	Public Function GetMemberInfo(Of TObject, TProperty)(expression As Expression(Of Func(Of TObject, TProperty))) As MemberInfo
		Dim member = TryCast(expression.Body, MemberExpression)
		If member IsNot Nothing Then
			Return member.Member
		End If

		Throw New ArgumentException("expression")
	End Function

	<Extension()>
	Public Function FromUTCToLocalTime(utcTime As Date) As Date
		Return DateTime.SpecifyKind(utcTime, DateTimeKind.Utc).ToLocalTime
	End Function

	<Extension()>
	Public Function MonthsDifference(startDate As Date, endDate As Date, Optional ReturnAboluteDifference As Boolean = False) As Integer
		Dim myMonthsDifference As Integer = Math.Abs((startDate.Month - endDate.Month) + 12 * (startDate.Year - endDate.Year))
		If startDate < endDate OrElse ReturnAboluteDifference Then
			Return myMonthsDifference
		Else
			Return -myMonthsDifference
		End If
	End Function

	<Extension()>
	Public Function FirstOfTheMonth(myDate As Date) As Date
		Return New Date(myDate.Year, myDate.Month, 1)
	End Function

	<Extension()>
	Public Function UtcCompare(firstDate As DateTime, secondDate As DateTime) As Integer
		Return DateTime.Compare(firstDate.ToUniversalTime, secondDate.ToUniversalTime)
	End Function

	<Extension()>
	Public Sub Save(updatedPublisher As PublisherData)
		Dim db As New CongregationDataContainerLocal

		Dim oldPublisher = db.PublisherDatas.Single(Function(x) x.PublisherID = updatedPublisher.PublisherID)
		oldPublisher.MobileTelephone = updatedPublisher.MobileTelephone
		db.SaveChanges()
	End Sub

	'http://themechanicalbride.blogspot.com/2007/03/symbols-on-steroids-in-c.html
	<Extension()>
	Public Function GetPropertySymbol(Of T, TResult)(obj As T, expr As Expression(Of Func(Of T, TResult))) As String
		Return DirectCast(expr.Body, MemberExpression).Member.Name
	End Function

	<Extension()>
	Public Function Reported(TimeRecord As PublisherCardData) As Boolean
		Return (TimeRecord.EnteredUtc < ConfigPropertyKeys.ReportLastSubmitted) AndAlso Not TimeRecord.IsHistorical
	End Function

	<Extension()>
	Public Function AppendFileDateExtension(StringToAppend As String) As String
		Return String.Format("{0}_{1}", StringToAppend, Now.ToString("yyyyMMddHHmmss"))
	End Function

End Module

